﻿define(["jquery", "bbcare", "jqprint", "echarts",
    "scprit/department/vm/assessmentScreening/peabodyScale.ui.js",
    "scprit/department/vm/assessmentScreening/assessmentScreeningQuestion.servers.js"
], function ($, $bb, $jqprint, echarts, $ui, $servers) {
    var event = {}
    event.init = function (obj) {
        var userId = obj.userId, type = obj.type, answerId = obj.answerId
        var hisParams = $servers.hisParams(userId, type, '1', '')
        if (window.__config__.role.indexOf('ReadOnly') > -1) {
            $('#modify').css({
                display: 'none'
            })
            $('#modifyRemark').css({
                display: 'none'
            })
        }
        var hisFn = function (data) {
            for (var i = 0; i < data.rows.length; i++) {
                data.rows[i].testAge = window.getAge(data.rows[i].birthday, data.rows[i].testTime)
                data.rows[i].testTime = data.rows[i].testTime.split(' ')[0]
            }
            $ui.historyInit({ "id": "#peabodyHis", "data": data.rows })
            if (!answerId) {
                answerId = $("#peabodyHis>li").eq(0).attr("answerId")
                totalFn(userId, type, answerId)
                $("#peabodyHis>li").eq(0).addClass("select").siblings().removeClass("select")
            } else {
                checkedFn(answerId)
                totalFn(userId, type, answerId)
            }
            //历史记录列表点击事件：
            $("#peabodyHis>li").click(function () {
                $(this).addClass("select").siblings().removeClass("select")
                answerId = $(this).attr("answerId")
                totalFn(userId, type, answerId)
            })
            /******************** begin 南方医院 添加备注 ********************/
            $("#modify").click(function () {
                if ($(this).attr("type") == "modify") {
                    $(".guides").attr("contentEditable", true).addClass("edit")
                    if ($("#guides").html() == "暂无指导意见") {
                        $("#guides").html("")
                    }
                    $(this).attr("type", "save").html('<i class="fa fa-check-square" aria-hidden="true"></i>确认修改')
                } else if ($(this).attr("type") == "save") {
                    $(".guides").removeAttr("contentEditable").removeClass("edit")
                    $(this).attr("type", "modify").html('<i class="fa fa-pencil-square" aria-hidden="true"></i>修改建议')
                    var guides = $.trim($("#guides").html())
                    var remark = $("#remark").length > 0 ? $.trim($("#remark").html()) : ""
                    if (!guides) {
                        $("#guides").html("暂无指导意见")
                        guides = "暂无指导意见"
                    }
                    modifyGuides(userId, answerId, guides, remark, type)
                }
            })
            $("#modifyRemark").click(function () {
                if ($(this).attr("type") == "modify") {
                    $(".remark").attr("contentEditable", true).addClass("edit")
                    if ($("#remark").html() == "暂无备注") {
                        $("#remark").html("")
                    }
                    $(this).attr("type", "save").html('<i class="fa fa-check-square" aria-hidden="true"></i>确认备注')
                } else if ($(this).attr("type") == "save") {
                    $(".remark").removeAttr("contentEditable").removeClass("edit")
                    $(this).attr("type", "modify").html('<i class="fa fa-pencil-square" aria-hidden="true"></i>修改备注')
                    var remark = $.trim($("#remark").html())
                    var guides = $.trim($("#guides").html())
                    if (!remark) {
                        $("#remark").html("暂无备注")
                        remark = "暂无备注"
                    }
                    modifyGuides(userId, answerId, guides, remark, type)
                }
            })
            /******************** end 南方医院 添加备注 ********************/
        }
        $servers.history(hisParams, hisFn)
        $(".info-box>div").resize(function () {
            var width = $(".info-box>div").width()
            $(".info-box>div>div").css({ "width": width })
            $(".info-box>div>div>canvas").css({ "width": width })
        })
    }
    var totalFn = function (userId, type, answerId) {
        getInfo(userId, answerId)
        getGuides(userId, type, answerId)
    }
    //获取评估记录详情：
    var getInfo = function (userId, evaId) {
        var reportParams = $servers.reportParams(userId, evaId)
        var reportFn = function (data) {
            //基本信息渲染：
            var diff = $servers.dateDiff(data.data.birthday, data.data.testTime)
            // data.data.acturalAge = $servers.getMonthAge(diff).monthAge;
            // data.data.correctAge = $servers.getMonthAge(diff,data.data.pregnancyWeek).monthAge;
            data.data.acturalAge = window.getAge(data.data.birthday, data.data.testTime)
            data.data.correctAge = window.getAge(data.data.birthday, data.data.testTime, 280 - data.data.pregnancyWeek)
            /**
             * 2022 04 24
             * 去掉 日期后的 00:00:00
             */
            if (data.data.birthday.indexOf('00:00:00') > -1) data.data.birthday = data.data.birthday.split(' ')[0]
            if (data.data.testTime.indexOf('00:00:00') > -1) data.data.testTime = data.data.testTime.split(' ')[0]
            /**
             * 大于24月隐藏掉纠正月龄
             */
            var birthDate = Math.floor(new Date(data.data.birthday).getTime() / 1000)
            var targetDate = Math.floor(new Date(data.data.testTime).getTime() / 1000)
            var oneDay = 3600 * 24
            data.data.showCorrectAge = (targetDate - birthDate) / oneDay <= 24

            $ui.userInfoInit({ "id": "#user-info", "data": data.data })
            $ui.userInfoInit({ "id": "#print-userInfo", "data": data.data })
            //绘制分数表格：
            var answerResult = JSON.parse(data.data.answerResult)
            var result = JSON.parse(data.data.result)
            result.moveScore = answerResult.itemTotalScore.motion * 1
            result.postureScore = answerResult.itemTotalScore.posture * 1
            result.grabScore = answerResult.itemTotalScore.grab * 1
            result.visionScore = answerResult.itemTotalScore.visuomotor * 1
            result.reflexScore = answerResult.itemTotalScore.reflex * 1
            result.operationScore = answerResult.itemTotalScore.practice * 1

            // 当月龄大于 11 个月时不需要显示反射这一条
            result.month = $servers.getMonthAge(diff, data.data.pregnancyWeek).month

            console.log(result)
            $ui.evaResultInit({ "id": "#record-score", "data": result })
            $ui.evaResultInit({ "id": "#print-recordScore", "data": result })
            //绘制分数简图：
            var trendsData1 = [], trendsData2 = []
            trendsData1[0] = ''
            trendsData1[1] = result.reflexStandard
            trendsData1[2] = result.postureStandard
            trendsData1[3] = result.moveStandard
            trendsData1[4] = result.operationStandard
            trendsData1[5] = result.grabStandard
            trendsData1[6] = result.visionStandard
            trendsData1[7] = ''

            trendsData2[0] = ''
            trendsData2[1] = result.CrossMotordiscuss
            trendsData2[2] = result.fineMotordiscuss
            trendsData2[3] = result.TotalMovementdiscuss
            trendsData2[4] = ''
            var dataX1 = ["标准分", "反射", "姿势", "移动", "实物操作", "抓握", "视觉-运动", "标准分"]
            var dataX2 = ["发育商", "粗大运动", "精细运动", "总体运动", "发育商"]
            fractionalDiagram("individualSketch", dataX1, trendsData1, 1, 20, 1, "标准分", "#individualSketch2")
            fractionalDiagram("totalScoreSketch", dataX2, trendsData2, 55, 150, 5, "发育商", "#totalScoreSketch2")

            //绘制项目完成情况表格
            //已知不同月龄段不同测试所对应的题目
            var quesArr = [
                { "month": "0", "posture": [1, 2], "motion": [1, 3], "grab": [1, 3] },
                { "month": "1", "posture": [3, 4], "visuomotor": [1, 3] },
                { "month": "2", "reflex": [1], "posture": [5, 7], "motion": [4, 5], "grab": [4, 5], "visuomotor": [4, 8] },
                { "month": "3", "posture": [8, 9], "motion": [6], "grab": [6], "visuomotor": [9] },
                { "month": "4", "reflex": [2], "posture": [10], "motion": [7, 8, 9], "grab": [7], "visuomotor": [10, 11] },
                { "month": "5", "posture": [11], "motion": [10, 11], "grab": [8, 10] },
                { "month": "6", "reflex": [3, 6], "posture": [12, 14], "motion": [12, 15], "grab": [11, 12], "visuomotor": [12, 14] },
                { "month": "7", "posture": [15], "motion": [16, 17], "grab": [13, 14], "visuomotor": [15, 17] },
                { "month": "8", "motion": [18], "grab": [15, 17], "visuomotor": [18, 19] },
                { "month": "9", "reflex": [7], "posture": [16], "motion": [19, 23], "visuomotor": [20, 21] },
                { "month": "10", "reflex": [8], "posture": [17, 18], "motion": [24, 28], "visuomotor": [22, 25] },
                { "month": "11", "motion": [29, 32], "grab": [18, 19], "visuomotor": [26, 28] },
                { "month": "12", "motion": [33, 35], "visuomotor": [29, 31], "practice": [1] },
                { "month": "13", "posture": [19], "motion": [36], "grab": [20], "visuomotor": [32, 35], "practice": [2, 3] },
                { "month": "14", "motion": [37, 38], "visuomotor": [36, 37] },
                { "month": "15-16", "motion": [39, 40], "grab": [21], "visuomotor": [38], "practice": [4, 5] },
                { "month": "17-18", "motion": [41, 44], "visuomotor": [39] },
                { "month": "19-20", "motion": [45, 46], "visuomotor": [40, 42], "practice": [6, 7] },
                { "month": "21-22", "motion": [47, 48], "visuomotor": [43] },
                { "month": "23-24", "motion": [49, 52], "visuomotor": [44], "practice": [8, 9] },
                { "month": "25-26", "motion": [53, 55], "visuomotor": [45, 47], "practice": [10] },
                { "month": "27-28", "motion": [56, 57], "visuomotor": [48, 50], "practice": [11] },
                { "month": "29-30", "motion": [58, 60], "visuomotor": [51, 53], "practice": [12, 13] },
                { "month": "31-32", "posture": [20], "motion": [61, 62], "visuomotor": [54] },
                { "month": "33-34", "motion": [63, 64], "visuomotor": [55], "practice": [14] },
                { "month": "35-36", "motion": [65], "visuomotor": [56] },
                { "month": "37-38", "motion": [66], "visuomotor": [57] },
                { "month": "39-40", "motion": [67], "visuomotor": [58, 59], "practice": [15, 16] },
                { "month": "41-42", "posture": [21], "motion": [68, 70], "visuomotor": [60, 63], "grab": [22, 23], "practice": [17] },
                { "month": "43-44", "posture": [22], "motion": [71, 72], "practice": [18] },
                { "month": "45-46", "posture": [23], "motion": [73, 75], "practice": [19, 20] },
                { "month": "47-48", "motion": [76, 77], "grab": [24] },
                { "month": "49-50", "grab": [25], "visuomotor": [64, 65] },
                { "month": "51-52", "posture": [24], "motion": [78, 80], "visuomotor": [66], "practice": [21, 22] },
                { "month": "53-54", "posture": [25], "motion": [81, 83], "grab": [26], "visuomotor": [67, 69] },
                { "month": "55-56", "motion": [84, 86], "visuomotor": [70] },
                { "month": "57-58", "posture": [26], "motion": [87] },
                { "month": "59-60", "posture": [27, 28], "motion": [88], "visuomotor": [71] },
                { "month": "61-62", "motion": [89] },
                { "month": "63-64" },
                { "month": "68-72", "posture": [29], "visuomotor": [72], "practice": [23, 24] },
                { "month": "72+", "posture": [30] }
            ]
            //数据格式：
            var quesArr2 = [
                { "title": "反射(0-11月)", "td": [], "type": "reflex" },
                { "title": "姿势", "td": [], "type": "posture" },
                { "title": "移动", "td": [], "type": "motion" },
                { "title": "实物操作", "td": [], "type": "practice" },
                { "title": "抓握", "td": [], "type": "grab" },
                { "title": "视觉-运动", "td": [], "type": "visuomotor" },
                { "title": "", "td": [], "type": "x" }
            ]
            var monthAge = getMonthAge(diff, data.data.pregnancyWeek)
            answerResult = answer(answerResult)
            var resData1 = getFlag(quesArr, answerResult, monthAge)
            var resData2 = dataSheet(resData1, quesArr2)
            $ui.tableInit({ "id": "#item-execution", "data": resData2 })
            $ui.tableInit({ "id": "#print-itemExecution", "data": resData2 })
        }
        $servers.report(reportParams, reportFn)
    }
    //完成结果处理：
    var answer = function (answerObj) {
        for (var item in answerObj) {
            if (!$.isEmptyObject(answerObj[item]) && (item == 'reflex' || item == 'posture' || item == 'grab' || item == 'motion' || item == 'visuomotor' || item == 'practice')) {
                var idArr = []
                for (var ids in answerObj[item]) {
                    idArr.push(ids)
                }
                var minId = Math.min.apply(null, idArr)
                if (minId > 1) {
                    for (var i = 1; i < minId; i++) {
                        answerObj[item][i] = 2
                    }
                }
            }
        }
        return answerObj
    }
    //完成情况数据处理：
    var getFlag = function (data, answerObj, monthAge) {
        for (var item in answerObj) {
            if (!$.isEmptyObject(answerObj[item]) && (item == 'reflex' || item == 'posture' || item == 'grab' || item == 'motion' || item == 'visuomotor' || item == 'practice')) {
                for (var i = 0; i < data.length; i++) {
                    var resScore = [], str = []
                    if (data[i][item]) {
                        if (data[i][item].length > 1) {
                            for (var j = data[i][item][0] * 1; j <= data[i][item][1] * 1; j++) {
                                if (answerObj[item][j] * 1 >= 0) {
                                    resScore.push(answerObj[item][j])
                                    if (answerObj[item][j] * 1 == 2) {
                                        str.push(j)
                                    }
                                }
                            }
                        } else {
                            if (answerObj[item][data[i][item][0]] * 1 >= 0) {
                                resScore = [answerObj[item][data[i][item][0]]]
                                if (answerObj[item][data[i][item][0]] * 1 == 2) {
                                    str.push(data[i][item][0])
                                }
                            }
                        }
                    }
                    var flag = item == "reflex" ? "rFlag" : item == "posture" ? "psFlag" : item == "motion" ? "mFlag" : item == "grab" ? "gFlag" : item == "visuomotor" ? "vFlag" : "prFlag"
                    if (resScore.length > 0) {
                        if (Math.max.apply(null, resScore) == 2) {
                            data[i][flag] = 2
                        } else if (Math.max.apply(null, resScore) == 1) {
                            data[i][flag] = 1
                        } else {
                            //区间：
                            if (data[i].month.indexOf("-") != "-1") {
                                var last = data[i].month.substring(3) * 1
                                if (monthAge <= last) {
                                    data[i][flag] = 'up'
                                } else {
                                    data[i][flag] = "down"
                                }
                            } else if (data[i].month.indexOf("+") != "-1") {
                                var age = data[i].month.substring(0, 2) * 1
                                if (monthAge < age) {
                                    data[i][flag] = 'up'
                                } else {
                                    data[i][flag] = "down"
                                }
                            } else {
                                age = data[i].month * 1
                                if (monthAge < age) {
                                    data[i][flag] = 'up'
                                } else {
                                    data[i][flag] = "down"
                                }
                            }
                        }
                    }
                    data[i][item] = str
                }
            } else if ($.isEmptyObject(answerObj[item]) && (item == 'reflex' || item == 'posture' || item == 'grab' || item == 'motion' || item == 'visuomotor' || item == 'practice')) {
                for (var i = 0; i < data.length; i++) {
                    data[i][item] = []
                }
            }
        }
        return data
    }
    //字符串转换成数组：
    var toArray = function (str) {
        var res = []
        if (typeof str == 'object') {
            for (var i = 0; i < str.length; i++) {
                res[i] = { "con": str[i] }
            }
        } else {
            str = str.toString()
            if (str.indexOf("-") >= 0) {
                res[0] = { 'con': str.substring(0, str.indexOf("-")) }
                res[1] = { 'con': str.substring(str.indexOf("-"), str.indexOf("-") + 1) }
                res[2] = { 'con': str.substring(str.indexOf("-") + 1) }
            } else {
                res[0] = { 'con': str.substring(0, 2) }
                res[1] = { 'con': str.substring(2, 3) }
            }
        }
        return res
    }
    var obj = function (quesObj, quesType) {
        var res = {}
        for (var item in quesObj) {
            if (item != "month" && item != "reflex" && item != "motion" && item != "posture" && item != "grab" && item != "visuomotor" && item != "practice") {
                res[item] = quesObj[item]
                if (quesObj[quesType]) {
                    res.con = toArray(quesObj[quesType])
                } else {
                    res.con = "&nbsp;"
                }

            }
        }
        return res
    }
    var dataSheet = function (quesArr, quesArr2) {
        for (var i = 0; i < quesArr.length; i++) {
            quesArr2[0].td.push(obj(quesArr[i], "reflex"))
            quesArr2[1].td.push(obj(quesArr[i], "posture"))
            quesArr2[2].td.push(obj(quesArr[i], "motion"))
            quesArr2[3].td.push(obj(quesArr[i], "practice"))
            quesArr2[4].td.push(obj(quesArr[i], "grab"))
            quesArr2[5].td.push(obj(quesArr[i], "visuomotor"))
            quesArr2[6].td.push({ "con": toArray(quesArr[i].month) })
        }
        return quesArr2
    }

    //分数简图：
    var fractionalDiagram = function (dom, dataX, dataY, min, max, interval, type, imgDom) {
        var myChart = echarts.init(document.getElementById(dom))
        var option = {
            textStyle: {
                fontSize: "15px"
            },
            tooltip: {
                trigger: 'item',
                formatter: function (params, ticket, callback) {
                    if (params.name == "标准分" || params.name == "发育商") {
                        return ""
                    } else {
                        return params.name + ":<br/>" + params.data
                    }
                }
            },
            grid: {
                show: true,
                top: "3%",
                left: '3%',
                right: '0',
                bottom: '5%',
                containLabel: true
            },
            xAxis: {
                show: 'false',
                position: "top",
                type: 'category',
                boundaryGap: false,
                data: dataX,
                axisLine: {
                    lineStyle: {
                        color: "#94A3B5"
                    }
                },
                axisLabel: {
                    textStyle: {
                        color: function (value, index) {
                            return value == "标准分" || value == "发育商" ? '#ababb3' : "#17c0e6"
                        }
                    },
                    interval: 0,
                    formatter: function (params, index) {
                        var value = params.split('')
                        var val = ''
                        for (var i = 0; i < value.length; i++) {
                            val += value[i] + "\n"
                        }
                        return val
                    }
                },
                axisTick: {
                    show: false
                }
            },
            yAxis: [
                {
                    type: 'value',
                    min: min,
                    max: max,
                    interval: interval,
                    axisLine: {
                        lineStyle: {
                            color: "#94A3B5"
                        }
                    },
                    axisLabel: {
                        textStyle: {
                            color: "#ababb3"
                        }
                    },
                    axisTick: {
                        show: false
                    }
                },
                {
                    type: 'value',
                    position: 'right',
                    min: min,
                    max: max,
                    interval: interval,
                    axisLine: {
                        lineStyle: {
                            color: "#94A3B5"
                        }
                    },
                    axisLabel: {
                        textStyle: {
                            color: "#ababb3"
                        }
                    },
                    axisTick: {
                        show: false
                    }
                }
            ],
            series: [
                {
                    type: 'scatter',
                    stack: '总量',
                    data: dataY,
                    itemStyle: {
                        normal: {
                            color: function (value) {
                                if (type == "标准分") {
                                    if (value.data * 1 <= 8) {
                                        return "#df5958"
                                    } else if (value.data * 1 >= 13) {
                                        return "#8bd195"
                                    } else {
                                        return "#f58344"
                                    }
                                }
                                if (type == "发育商") {
                                    if (value.data * 1 <= 90) {
                                        return "#df5958"
                                    } else if (value.data * 1 >= 110) {
                                        return "#8bd195"
                                    } else {
                                        return "#f58344"
                                    }
                                }
                            }
                        }
                    },
                    hoverAnimation: false
                }
            ]
        }
        myChart.setOption(option)
        $(imgDom).html('<img src="' + myChart.getDataURL({ type: "png" }) + '" style="width: 100%;height:100%; "/>')
    }

    //获取指导意见
    var getGuides = function (userId, exam, evaId) {
        var params = $servers.getGuidesParams(userId, exam, evaId)
        var guidesFn = function (data) {
            if (data.data) {
                $("#guides,#printGuides").html(data.data.guide)
                if ($("#remark").length > 0) $("#remark").html(data.data.remark)
            } else {
                $("#guides,#printGuides").html("暂无指导意见")
                if ($("#remark").length > 0) $("#remark").html("暂无备注")
            }
        }
        $servers.getGuides(params, guidesFn)
    }
    //更改指导意见：
    var modifyGuides = function (userId, evaId, guides, remark, exam) {
        var params1 = $servers.modifyGuidesParams(userId, evaId, guides, remark)
        var guidesFn = function (data2) {
            getGuides(userId, exam, evaId)
        }
        $servers.modifyGuides(params1, guidesFn)
    }
    var checkedFn = function (answerId) {
        $("#peabodyHis").find("li").each(function (i) {
            var $this = $(this)
            if ($this.attr("answerId") == answerId) {
                $(this).addClass("select").siblings().removeClass("select")
            }
        })
    }
    //获取宝宝当前月龄：
    var getMonthAge = function (acturalDay, pregnanceDay) {
        var monthAge
        if (acturalDay / 365 >= 2) {
            monthAge = Math.floor(acturalDay / 30.4)
        } else {
            if (pregnanceDay < 37 * 7) {
                var dayDiff = acturalDay - (280 - pregnanceDay)
                if (dayDiff <= 0) {
                    monthAge = 0
                } else {
                    monthAge = Math.floor(dayDiff / 30.4)
                }
            } else {
                monthAge = Math.floor(acturalDay / 30.4)
            }
        }
        return monthAge
    }
    return event
})